package com.gydz.gydzbaseframeworkboot.SgsE.controller;

import com.gydz.gydzbaseframeworkboot.Common.utils.export.ExcelUtil;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageParam;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.PageUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.page.TableDataInfo;
import com.gydz.gydzbaseframeworkboot.Common.utils.result.ResultUtils;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.domain.TableSelect;
import com.gydz.gydzbaseframeworkboot.Common.utils.sqlUtil.service.SqlUtilsService;
import com.gydz.gydzbaseframeworkboot.CommonConfig.domain.BasisData;
import com.gydz.gydzbaseframeworkboot.CommonConfig.service.BasisDataService;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.EInterfaceIsup;
import com.gydz.gydzbaseframeworkboot.SgsE.domain.SqlStatements;
import com.gydz.gydzbaseframeworkboot.SgsE.service.EInterfaceIsupService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.JingTaiService;
import com.gydz.gydzbaseframeworkboot.SgsE.service.YingSheService;
import com.gydz.gydzbaseframeworkboot.SystemControl.utils.Log;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/EInterfaceIsup")
public class EInterfaceIsupQueryController {
    private static final Logger log = LoggerFactory.getLogger(EInterfaceIsupQueryController.class);

    @Autowired
    YingSheService yingSheService;

    @Autowired
   private EInterfaceIsupService eInterfaceIsupService;


   @Autowired
   private SqlUtilsService sqlUtilsService;

    @Autowired
    private JingTaiService jingTaiService;

    @Autowired
    private BasisDataService basisDataService;

    @ResponseBody
    @Log(remark = "查询E接口Isup信令记录")
    @PostMapping("/list")
    public void list(HttpServletResponse httpServletResponse, @ModelAttribute("EInterfaceIsup") EInterfaceIsup eInterfaceIsup) throws IOException {
        TableSelect tableSelect = new TableSelect();
        tableSelect.setTableSchema("ss7");
        tableSelect.setPrefix("sgs_isup_");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        System.out.println("startime==="+eInterfaceIsup.getDtsTimeSelect());
        if(eInterfaceIsup.getDtsTime() == null){
            ResultUtils result =  ResultUtils.fail("查询E接口Isup信令记录失败,请选择查询时间范围");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }else {
            tableSelect.setDateMin(dateFormat.format(eInterfaceIsup.getDtsTime()));
        }
        if(eInterfaceIsup.getDteTime()== null){
            eInterfaceIsup.setDteTime(new Date());
        }
        tableSelect.setDateMax(dateFormat.format(eInterfaceIsup.getDteTime()));
        List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
        if(tableList.isEmpty()){
            ResultUtils result =  ResultUtils.fail("没有该时间范围的表");
            ResultUtils.responseResult(httpServletResponse,result);
            return ;
        }
        PageUtils.startPage(new PageParam(eInterfaceIsup.getiDisplayStart(),eInterfaceIsup.getiDisplayLength(),eInterfaceIsup.getsSortDir(),eInterfaceIsup.getsSortCol()));
        eInterfaceIsup.setTableNameList(tableList);
        List<EInterfaceIsup> list = eInterfaceIsupService.selectEInterfaceIsupList(eInterfaceIsup);
        //翻译回填字段
        if(list.size()!=0) {
            translationDataToProcess(list);
        }
        TableDataInfo tableDataInfo = PageUtils.getDataTable(list);
        ResultUtils result =  ResultUtils.succ(200,"查询E接口Isup信令成功",tableDataInfo);
        ResultUtils.responseResult(httpServletResponse,result);
    }

    @ResponseBody
    @Log(remark = "导出E接口isup信令记录")
    @RequestMapping("/exportData")
    public void exportData(HttpServletRequest request, @ModelAttribute("EInterfaceIsup") EInterfaceIsup eInterfaceIsup, HttpServletResponse response) throws IOException {
    String[] excelHeader = {"触发时间", "主叫MSISDN", "被叫MSISDN", "协议描述", "信令info", "OPC", "DPC", "SLS", "CIC", "MTP消息类型", "ISUP消息类型", "ISUP释放原因", "事件指示", "连接号码", "设备号", "端口号", "时隙号", "数据长度", "数据内容"};
    String[] ds_titles = {"dtSTime",  "vcCallingNumber", "vcCalledNumber", "vcProtocol", "vcInfo", "intOpc", "intDpc", "intSLS", "intCIC", "intMTPType", "uintIsupType", "uintCauseIndicator", "uintEventInd", "vcConnectedNumber", "intCardNo", "intCardPort", "intCardSlot", "intTotalLen", "sourceData"};
    int[] widths = {256*25,  256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*19, 256*30}; // 确保宽度数组与列数匹配
    int[] ds_format = {2, 2,  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}; // 确保格式数组与列数匹配

    TableSelect tableSelect = new TableSelect();
    tableSelect.setTableSchema("ss7"); // 修改为 ss7 表
    tableSelect.setPrefix("sgs_isup_"); // 修改为 sgs_isup_ 前缀
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    // 使用 EInterfaceIsup 的时间范围属性
    if (eInterfaceIsup.getDtsTime() == null) {
        ResultUtils result = ResultUtils.fail("查询E接口isup信令失败,请选择查询时间范围");
        ResultUtils.responseResult(response, result);
        return;
    } else {
        tableSelect.setDateMin(dateFormat.format(eInterfaceIsup.getDtsTime()));
    }

    if (eInterfaceIsup.getDteTime() == null) {
        eInterfaceIsup.setDteTime(new Date());
    }
    tableSelect.setDateMax(dateFormat.format(eInterfaceIsup.getDteTime()));

    List<String> tableList = sqlUtilsService.selectTabeName(tableSelect);
    if (tableList.isEmpty()) {
        ResultUtils result = ResultUtils.fail("没有该时间范围的表");
        ResultUtils.responseResult(response, result);
        return;
    }

    eInterfaceIsup.setTableNameList(tableList);
    List<EInterfaceIsup> list = eInterfaceIsupService.selectEInterfaceIsupList(eInterfaceIsup); // 使用 EInterfaceIsup 服务
    // 翻译回填字段
    if (list == null || list.isEmpty()) {
    // 处理空列表的情况
    System.out.println("The list is empty or null.");
    return;
}
try {
    translationDataToProcess(list);
} catch (Exception e) {
    // 捕获所有其他异常并处理
    System.err.println("An unexpected error occurred: " + e.getMessage());
    // 记录日志
    log.error("Unexpected error", e);
}

    try {
        List<Map<String, Object>> data = new ArrayList<>();
        if (list != null && !list.isEmpty()) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int index = 1;
            for (EInterfaceIsup rdata : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("index", index);
                map.put("dtSTime", format.format(rdata.getDtsTime()));
//                map.put("uintInterfaceID", rdata.getUintInterfaceID());
                map.put("vcCallingNumber", rdata.getVcCallingNumber());
                map.put("vcCalledNumber", rdata.getVcCalledNumber());
                map.put("vcProtocol", rdata.getVcProtocol());
                map.put("vcInfo", rdata.getVcInfo());
                map.put("intOpc", rdata.getIntOpc());
                map.put("intDpc", rdata.getIntDpc());
                map.put("intSLS", rdata.getIntSLS());
                map.put("intCIC", rdata.getIntCIC());
                map.put("intMTPType", rdata.getIntMTPType());
                map.put("uintIsupType", rdata.getUintIsupType());
                map.put("uintCauseIndicator", rdata.getUintCauseIndicator());
                map.put("uintEventInd", rdata.getUintEventInd());
                map.put("vcConnectedNumber", rdata.getVcConnectedNumber());
                map.put("intCardNo", rdata.getIntCardNo());
                map.put("intCardPort", rdata.getIntCardPort());
                map.put("intCardSlot", rdata.getIntCardSlot());
                map.put("intTotalLen", rdata.getIntTotalLen());
                map.put("sourceData", rdata.getSourceData());
                index++;
                data.add(map);
            }
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddHHmmss");
        ExcelUtil.export("E接口isup信令记录数据" + format.format(new Date()), "数据列表", excelHeader, ds_titles, ds_format, widths, data, request, response);
    } catch (Exception e) {
        log.error("导出数据异常", e);
    }
}




   //翻译填充数据
   public List<EInterfaceIsup> translationDataToProcess(List<EInterfaceIsup> signalingIsup){

       //dpc opc静态数据
       List<BasisData> dpcOpcList = basisDataService.selectBasisDataAllIsYingShe(SqlStatements.STATIC_TABLENAME_DPC_OPC.getSql());

       //翻译ISUP消息类型
       List<BasisData> isuptypeList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_ISUP_TYPE.getSql());

       //翻译isup释放原因
       List<BasisData> isupReleaseTheReasonList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_ISUP_RELEASE_THE_REASON.getSql());
//
//        //翻译ISUP业务类型             List
//        List<BasisData> transmrList = BasisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_TRANS_MR.getSql());

       //翻译接口类型                 List
       List<BasisData> uintInterfaceIDList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_INTERFACE_ID.getSql());

       //翻译MTP类型                List
       List<BasisData> intMtpTypeList = basisDataService.selectBasisDataAll(SqlStatements.STATIC_TABLENAME_MTP_TYPE.getSql());


       String beiJiaoStr;
       String zhuJiaoStr;
       for (EInterfaceIsup b : signalingIsup) {
           //处理原始数据内容
           JSONObject jsonObject = JSONObject.fromObject(b.getSourceData());
           JSONArray frameData = jsonObject.getJSONArray("frame_data");
           String sourceData = "";
           String newSourceData = "";
           for (int i = 0; i < frameData.size(); i++) {
               sourceData += frameData.getJSONObject(i).getString("text");
               newSourceData += frameData.getJSONObject(i).getString("text");
               if(i+1 != frameData.size()){
                   sourceData += ",\n\n\n";
               }
           }
           b.setSourceData(sourceData);
           //翻译dpc和opc
           for(BasisData bdm : dpcOpcList){
               if(bdm.getActualvalue().equals(b.getIntOpc())){
                   b.setIntOpc(bdm.getShowvalue());
               }

               if(bdm.getActualvalue().equals(b.getIntDpc())){
                   b.setIntDpc(bdm.getShowvalue());
               }
           }

           //翻译ISUP消息类型
           for(BasisData bdm : intMtpTypeList){
               if(bdm.getActualvalue().equals(b.getIntMTPType())){
                   b.setIntMTPType(bdm.getShowvalue());
                   break;
               }
           }

           //翻译ISUP释放类型
           for(BasisData bdm : isupReleaseTheReasonList){
               if(bdm.getActualvalue().equals(b.getUintCauseIndicator())){
                   b.setUintCauseIndicator(bdm.getShowvalue());
                   break;
               }
           }


           //翻译ISUP消息类型
           for(BasisData bdm : isuptypeList){
               if(bdm.getActualvalue().equals(b.getUintIsupType())){
                   b.setUintIsupType(bdm.getShowvalue());
                   break;
               }
           }

           //翻译接口类型
           for(BasisData bdm : uintInterfaceIDList){
               if(bdm.getActualvalue().equals(b.getUintInterfaceID())){
                   b.setUintInterfaceID(bdm.getShowvalue());
                   break;
               }
           }

           //取原始数据长度
           b.setIntTotalLen(b.getSourceData().length() + "");
       }


       return signalingIsup;
   }


}
